<?php

class multitender_action_rubrics extends multitender_action {

    private $list = array();

    function __construct() {
        parent::__construct();
        $this->list = $this->db->GetArray("SELECT id, parent, name FROM rubric ORDER BY parent ASC");
    }

    private function SelectArrayToRubricID($sql) {

        $arr = $this->db->GetArray($sql);
        $result = array();
        foreach ($arr as $key => $val) {
            $result[$val[0]] = $val[1];
        }
        return $result;
    }

    private function GetRubricsByCountry($country=1, $type=1) {

        $fr = (int) ($country - 1) * 100;
        $tr = (int) $country * 100;

        $sql = " SELECT rubric_id, count(*) as cnt FROM `item` USE INDEX (region_id_2) WHERE rubric_id<>0 ";
        $sql.= " AND region_id > $fr AND region_id <= $tr ";
        $sql.= " GROUP BY rubric_id HAVING cnt>0 ";

        $counts = $this->db->GetArray($sql);
        /* $sql = "SELECT rubric_id, count(*) as cnt FROM `item` ";

          $all = $this->SelectArrayToRubricID($sql . "WHERE rubric_id<>0 AND region_id > 0 GROUP BY rubric_id HAVING cnt > 0");
          $ct1 = $this->SelectArrayToRubricID($sql . "WHERE rubric_id<>0 AND region_id < ".($fr+1)." GROUP BY rubric_id HAVING cnt > 0");
          $ct2 = $this->SelectArrayToRubricID($sql . "WHERE rubric_id<>0 AND region_id > $tr GROUP BY rubric_id HAVING cnt > 0");

          foreach ($all as $key => $val) {
          $result[$key] = $val - (isset($ct2[$key]) ? $ct2[$key] : 0) - (isset($ct1[$key]) ? $ct2[$key] : 0);
          }
         */
        // Индексация массива в качестве индекса RUBRIC_ID
        $result = array();
        foreach ($counts as $key => $val) {
            $result[$val[0]] = $val[1];
        }
        // Расчёт для родительских количество тендеров в родительской категории.
        foreach ($this->list as $rubric) {
            if ($rubric['parent'] > 0)
                @$result[$rubric['parent']] += $result[$rubric['id']];
        }
        return $result;
    }

    private function GetTreeFor($country=1) {

        $counts = $this->GetRubricsByCountry($country);

        if ($country == 1) {
            $regions_link = "&search[reg][100]=on";
        } else {
            $regions_link = "&search[reg][200]=on&search[reg][300]=on&search[reg][400]=on&search[reg][500]=on&search[reg][600]=on";
        }

        $rubricsHTML = array();
        $subrubric = array();
        foreach ($this->list as $rubric) {

            if ($rubric['name'] == 'Другое') {
                continue;
            }

            if ($rubric['parent'] == 0) {

                $rubricsHTML[$rubric['id']] =
                        '<h3><a href="#" id="' . $rubric['id'] . '">' . $rubric['name'] . '</a><span>' . $counts[$rubric['id']] . '</span></h3>
                         <div>
                            <p><a href="/tenders/?search[rubric][' . $rubric['id'] . ']' . $regions_link . '">Все закупки раздела</a></p>
                            {sub}
                         </div>';
                if (!isset($subrubric[$rubric['id']])) {
                    $subrubric[$rubric['id']] = '';
                }
            } else {
                if (!is_numeric($counts[$rubric['id']])) {
                    $counts[$rubric['id']] = 0;
                }
                $subrubric[$rubric['parent']] .='
                <p><a href="/tenders/?search[rubric][' . $rubric['id'] . ']' . $regions_link . '">' . $rubric['name'] . '</a><span>' . $counts[$rubric['id']] . '</span></p>';
            }
        }

        foreach ($rubricsHTML as $id => &$rubric) {
            $rubric = str_replace('{sub}', $subrubric[$id], $rubric);
        }
        $rubricsHTML = implode('', $rubricsHTML);

        return $rubricsHTML;
    }

    public function run() {
        
        $this->conf['page_title'] = 'Закупки по категориям';
        $tpl = $this->new_tpl();
        $tpl->caching = TRUE;
        $tpl->cache_lifetime = 60 * 60 * 30;

        if (!$tpl->is_cached("rubrics.tpl")) {
            $rubric_id = @ (int) $_GET['id'];

            $tpl->assign('rubRUS', $this->GetTreeFor(1));
            $tpl->assign('rubSNG', $this->GetTreeFor(2));

            if ($rubric_id) {
                $tpl->assign('current', $rubric_id);
            }
            $result="<!-- no cache -->";
        } else {
            $result="<!-- from Cache -->";
        }

        return $result . $tpl->fetch('rubrics.tpl');
    }

//function run
}